package com.example.stock.ui.login;

import android.app.Application;
import android.text.TextUtils;
import android.util.Patterns;

import com.example.stock.R;
import com.example.stock.base.BaseViewModel;
import com.example.stock.http.ApiException;
import com.example.stock.http.ICallback;
import com.example.stock.http.ResponseCallback;
import com.example.stock.model.GoodsOrderBean;
import com.example.stock.util.DBUtil;
import com.example.stock.util.SharedPreferencesUtils;
import com.example.stock.util.Utils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

public class LoginViewModel extends BaseViewModel {

    private final MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>();
    private final MutableLiveData<Boolean> loginResult = new MutableLiveData<>();

    public LoginViewModel(@NonNull Application application) {
        super(application);
    }


    LiveData<LoginFormState> getLoginFormState() {
        return loginFormState;
    }

    public MutableLiveData<Boolean> getLoginResult() {
        return loginResult;
    }

    public void loginCheck(String str) {
        api.getArriveOrder(str + "uapws/service/nc.ws.base.intf.IBusiPDABillService/getArriveorder").enqueue(new ResponseCallback<String>(this) {
            @Override
            public void onSuccess(String o) {
                loginResult.setValue(true);
            }

            @Override
            public void onFailure(ApiException e) {
                String message = e.getMessage();
                if (message != null && !TextUtils.isEmpty(message) && message.contains("soap:Envelope")) {
                    loginResult.setValue(true);
                } else {
                    loginResult.setValue(false);
                    Utils.getInstance().showToast(e.getMessage());
                }
            }
        });
    }

    public void loginDataChanged(String username, String password) {
        if (!isUserNameValid(username)) {
            loginFormState.setValue(new LoginFormState(R.string.invalid_ip, null));
        } else if (!isPasswordValid(password)) {
            loginFormState.setValue(new LoginFormState(null, R.string.invalid_port));
        } else {
            loginFormState.setValue(new LoginFormState(true));
        }
    }

    // A placeholder username validation check
    private boolean isUserNameValid(String username) {
        if (username == null) {
            return false;
        }
        if (!TextUtils.isEmpty(username)) {
            return Patterns.IP_ADDRESS.matcher(username).matches();
        } else {
            return !username.trim().isEmpty();
        }
    }

    // A placeholder password validation check
    private boolean isPasswordValid(String password) {
        return password != null && password.trim().length() == 4;
    }
}